package edu.stanford.junction.tictactoe;

import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

public class Player {
	private String playerId;
	private String firstName;
	private String lastName;
	private String avatarURL;
	
	private int playerTile;
	
	public Player(String playerId,
				  String firstName,
				  String lastName,
				  String avatarURL,
				  int playerTile) {
		this.playerId = playerId;
		this.firstName = firstName;
		this.lastName = lastName;
		this.avatarURL = avatarURL;
		setPlayerTile(playerTile);
	}
	
	public Player(JSONObject data, int playerTile) {
		this.playerId = data.optString("playerId");
		this.firstName = data.optString("firstName");
		this.lastName = data.optString("lastName");
		this.avatarURL = data.optString("avatarURL");
		setPlayerTile(playerTile);
	}
	
	private void setPlayerTile(int playerTile) {
		if (playerTile == Board.empty_slot) {
			Random rgen = new Random();
			if (rgen.nextBoolean()) this.playerTile = Board.player_o;
			else this.playerTile = Board.player_x;
		}
		else this.playerTile = playerTile;
	}
	
	public void setPlayerId(String newID) {this.playerId = newID;}
	public String getPlayerId() {return playerId;}
	public String getFirstName() {return firstName;}
	public String getLastName() {return lastName;}
	public String getAvatarURL() {return avatarURL;}
	public int getPlayerTile() {return playerTile;}
	
	public JSONObject toJSON() {
		JSONObject j = new JSONObject();
		try {
			j.put("playerId", playerId);
			j.put("firstName", firstName);
			j.put("lastName", lastName);
			j.put("avatrURL", avatarURL);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return j;
	}	
}
